
#include <QtGui/QMenuBar>
#include <QtGui/QGridLayout>

#include <QtSql/QSqlQuery>
#include <QtSql/QSqlDatabase>

#include <QDebug>
#include "mainwindow.h"
#include "graphicbutton.h"
#include "global.h"

MainWindow::MainWindow(QWidget *parent) :
    QDialog(parent)
{
    resize(800,480);
    //主界面整体布局管理
    QVBoxLayout *mainlayout = new QVBoxLayout;
    QGridLayout *layout = new QGridLayout;
    for (int i=0; i<NUM_OF_BTN_PER_PAGE; ++i)
    {
        gra_button[i] = new GraphicButton(i,this);
        layout->addWidget(gra_button[i], i/NUM_OF_BTN_PER_ROW, i%NUM_OF_BTN_PER_ROW);
    }
    mainlayout->addLayout(layout);
    setLayout(mainlayout);

    connect( this, SIGNAL(sig_order_to_send(int)), this->parentWidget(), SLOT(order_to_send(int)) );

    create_initial_show();
}




void MainWindow::create_initial_show()
{
    btn_of_current_page.eraseAllRecord();
    QSqlDatabase::database().transaction();
    QSqlQuery query, query_logo;
    query.exec("SELECT * FROM locate_information_table order by id asc");
    for(int i = 0; i<NUM_OF_BTN_PER_PAGE && query.next()==true; ++i)
    {
        QString num = query.value(0).toString();
        QString dev_name = query.value(5).toString();
        QString locate_inf = dev_name +tr("\n")+ query.value(1).toString() + query.value(2).toString()
                     +query.value(3).toString()+query.value(4).toString();

        gra_button[i]->init_const_member();
        gra_button[i]->set_geo_description_and_num(locate_inf, num);

        int btn_num = num.toInt();
        if( NodeStatus::Instance()->isNodeStart(btn_num) )
            gra_button[i]->set_start_led(TURN_ON);
        else
            gra_button[i]->set_start_led(TURN_OFF);

        if( NodeStatus::Instance()->isNodeFault(btn_num) )
            gra_button[i]->set_fault_led(TURN_ON);
        else
            gra_button[i]->set_fault_led(TURN_OFF);

        if( NodeStatus::Instance()->isNodeFedback(btn_num) )
            gra_button[i]->set_fedback_led(TURN_ON);
        else
            gra_button[i]->set_fedback_led(TURN_OFF);

        query_logo.exec(tr("SELECT * FROM device_logoinf_table WHERE device_name='%1' ").arg(dev_name));
        if(query_logo.next())
        {
            QString filepath = query_logo.value(1).toString();
            gra_button[i]->set_device_logo(filepath);
        }

        btn_of_current_page.addOneRecord(num.toInt(), TAIL,SysMode::FULL_MODE);
    }
    QSqlDatabase::database().commit();
}

void MainWindow::goto_previous_page()
{
    if(SysMode::Instance()->getMode()!=SysMode::FULL_MODE)
    {
        return;
    }

    if(btn_of_current_page.isFistPage())
    {
        qDebug()<<"This is already the first page!";
        return;
    }
    btn_of_current_page.setToLastPage(false);
    int current_min_number = btn_of_current_page.getMinID();
    btn_of_current_page.eraseAllRecord();
    qDebug()<<"int current_min_number = btn_of_current_page.getMinID()  "<<current_min_number;
    QSqlQuery query, query_logo;
    query.exec(QString("SELECT * FROM locate_information_table where id < %1 order by id desc LIMIT %2").arg(current_min_number).arg(NUM_OF_BTN_PER_PAGE));

    int cnt = 0;
    QString filepath,num,dev_name,locate_inf;
    for( cnt = NUM_OF_BTN_PER_PAGE - 1;  cnt>=0 && query.next()==true;  --cnt )
    {
        num = query.value(0).toString();
        dev_name = query.value(5).toString();
        locate_inf = dev_name +tr("\n")+ query.value(1).toString() + query.value(2).toString()
                     +query.value(3).toString()+query.value(4).toString();
        gra_button[cnt]->init_const_member();
        gra_button[cnt]->set_geo_description_and_num(locate_inf, num);

        int btn_num = num.toInt();
        if( NodeStatus::Instance()->isNodeStart(btn_num) )
            gra_button[cnt]->set_start_led(TURN_ON);
        else
            gra_button[cnt]->set_start_led(TURN_OFF);

        if( NodeStatus::Instance()->isNodeFault(btn_num) )
            gra_button[cnt]->set_fault_led(TURN_ON);
        else
            gra_button[cnt]->set_fault_led(TURN_OFF);

        if( NodeStatus::Instance()->isNodeFedback(btn_num) )
            gra_button[cnt]->set_fedback_led(TURN_ON);
        else
            gra_button[cnt]->set_fedback_led(TURN_OFF);

        query_logo.exec(tr("SELECT * FROM device_logoinf_table WHERE device_name='%1' ").arg(dev_name));
        if(query_logo.next())
        {
            filepath = query_logo.value(1).toString();
            gra_button[cnt]->set_device_logo(filepath);
        }
        else //have no logo
        {
            gra_button[cnt]->set_device_logo("");
        }
        //add a record to the btn_of_current_page table
        btn_of_current_page.addOneRecord(num.toInt(),HEAD,SysMode::FULL_MODE);
    }

    //this means it has came to the first page
    if( cnt >= 0 )
    {
        btn_of_current_page.eraseAllRecord();
        query.exec(QString("SELECT * FROM locate_information_table order by id LIMIT %1").arg(NUM_OF_BTN_PER_PAGE));
        for( cnt= 0; cnt<NUM_OF_BTN_PER_PAGE && query.next()==true; ++cnt )
        {
            num = query.value(0).toString();
            dev_name = query.value(5).toString();
            locate_inf = dev_name +tr("\n")+ query.value(1).toString() + query.value(2).toString()
                         +query.value(3).toString()+query.value(4).toString();
            gra_button[cnt]->init_const_member();
            gra_button[cnt]->set_geo_description_and_num(locate_inf, num);

            int btn_num = num.toInt();
            if( NodeStatus::Instance()->isNodeStart(btn_num) )
                gra_button[cnt]->set_start_led(TURN_ON);
            else
                gra_button[cnt]->set_start_led(TURN_OFF);

            if( NodeStatus::Instance()->isNodeFault(btn_num) )
                gra_button[cnt]->set_fault_led(TURN_ON);
            else
                gra_button[cnt]->set_fault_led(TURN_OFF);

            if( NodeStatus::Instance()->isNodeFedback(btn_num) )
                gra_button[cnt]->set_fedback_led(TURN_ON);
            else
                gra_button[cnt]->set_fedback_led(TURN_OFF);

            query_logo.exec(tr("SELECT * FROM device_logoinf_table WHERE device_name='%1' ").arg(dev_name));
            if(query_logo.next())
            {
                filepath = query_logo.value(1).toString();
                gra_button[cnt]->set_device_logo(filepath);
            }
            else //have no logo
            {
                gra_button[cnt]->set_device_logo("");
            }
            //add a record to the btn_of_current_page table
            btn_of_current_page.addOneRecord(num.toInt(),TAIL,SysMode::FULL_MODE);
        }
        btn_of_current_page.setToFisrtPage(true);
    }
}


void MainWindow::goto_next_page()
{
    if(SysMode::Instance()->getMode()!=SysMode::FULL_MODE)
    {
        return;
    }

    if( btn_of_current_page.isLastPage())
    {
        qDebug()<<"This is already the last page!";
        return;
    }

    int current_max_number = btn_of_current_page.getMaxID();
    if(current_max_number == INVALID_MAX_ID)
        return;
    btn_of_current_page.setToFisrtPage(false);

#if DEBUG_ON
    qDebug()<<"int current_max_number = btn_of_current_page.getMaxID()  "<<current_max_number;
#endif

    QSqlQuery query, query_logo;
    query.exec(QString("SELECT * FROM locate_information_table where id > %1 ").arg(current_max_number));

    bool erase_falg=true;
    int cnt = 0;
    for( cnt= 0; cnt<NUM_OF_BTN_PER_PAGE && query.next()==true; ++cnt )
    {
        if(erase_falg)
        {
            erase_falg = false;
            btn_of_current_page.eraseAllRecord();
        }

        QString num = query.value(0).toString();
        QString dev_name = query.value(5).toString();
        QString locate_inf = dev_name +tr("\n")+ query.value(1).toString() + query.value(2).toString()
                     +query.value(3).toString()+query.value(4).toString();
        gra_button[cnt]->init_const_member();
        gra_button[cnt]->set_geo_description_and_num(locate_inf, num);

        int btn_num = num.toInt();
        if( NodeStatus::Instance()->isNodeStart(btn_num) )
            gra_button[cnt]->set_start_led(TURN_ON);
        else
            gra_button[cnt]->set_start_led(TURN_OFF);

        if( NodeStatus::Instance()->isNodeFault(btn_num) )
            gra_button[cnt]->set_fault_led(TURN_ON);
        else
            gra_button[cnt]->set_fault_led(TURN_OFF);

        if( NodeStatus::Instance()->isNodeFedback(btn_num) )
            gra_button[cnt]->set_fedback_led(TURN_ON);
        else
            gra_button[cnt]->set_fedback_led(TURN_OFF);

        query_logo.exec(tr("SELECT * FROM device_logoinf_table WHERE device_name='%1' ").arg(dev_name));
        if(query_logo.next())
        {
            QString filepath = query_logo.value(1).toString();
            gra_button[cnt]->set_device_logo(filepath);
        }
        else //have no logo
        {
            gra_button[cnt]->set_device_logo("");
        }

        //add a record to the btn_of_current_page table
        btn_of_current_page.addOneRecord(num.toInt(),TAIL,SysMode::FULL_MODE);
    }

    if( cnt == 0 )
    {
        btn_of_current_page.setToLastPage(true);
        qDebug()<<"This is already the last page!";
        return;
    }

    if( cnt >0 && cnt < NUM_OF_BTN_PER_PAGE)
    {
        while( cnt<NUM_OF_BTN_PER_PAGE)
        {
            gra_button[cnt]->set_undefined_state();
            cnt++;
        }
        btn_of_current_page.setToLastPage(true);
    }
}


void MainWindow::gra_btn_clicked_msg(int btn_number)
{
    //此处判断按键信息是否有效
    qDebug()<<"button"<<btn_number<<"clicked...";

    /*  判断
            是否处于总线禁止状态
            是否处于手控点屏蔽状态
            是否定义/是否故障/是否启动/是否反馈
    */
    if( NodeStatus::Instance()->isBusAllow() &&
        NodeStatus::Instance()->isNodeDefined(btn_number) &&
        !NodeStatus::Instance()->isNodeForbid(btn_number) &&
        !NodeStatus::Instance()->isNodeFault(btn_number) &&
        !NodeStatus::Instance()->isNodeStart(btn_number)
    )
    {
        //将启动/停止命令的发送留给MainWindow的父类MainUI，便于统一完整模式和简化模式
        emit sig_order_to_send(btn_number);

        NodeStatus::Instance()->setNodeStatus(btn_number,NodeStatus::START_BIT);
    }
}
